package com.cykj.admin.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.ocr_api20210707.Client;
import com.aliyun.ocr_api20210707.models.RecognizeBusinessLicenseRequest;
import com.aliyun.ocr_api20210707.models.RecognizeBusinessLicenseResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.cykj.admin.vo.CompanyVO;

import java.io.InputStream;
import java.util.HashMap;

/**
 * @BelongsProject:@BelonqsPackage:com.cykj.admin.util
 * @Author:jiangna
 * @CreateTime:2025-09-01 11:12
 */
public class LicenseUtil {
    // 客户端创建逻辑不变（精简配置初始化）
    private static Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId("LTAI5t6jEcFtBiddoPHJEjAa")
                .setAccessKeySecret("lM2sBajxccPWiLWmxI16l8ZeBgHIi3")
                .setEndpoint("ocr-api.cn-hangzhou.aliyuncs.com");
        return new Client(config);
    }

    public static CompanyVO getCompanyInfo(String licenseIcon) {
//        String imgPath = "D:\\Desktop\\222.png"; // 图片路径可灵活修改

        // try-with-resources自动关闭流，避免资源泄漏
        try (InputStream imgStream = com.aliyun.darabonba.stream.Client.readFromFilePath(licenseIcon)) {
            Client client = createClient();
            RecognizeBusinessLicenseRequest request = new RecognizeBusinessLicenseRequest().setBody(imgStream);
            RuntimeOptions runtime = new RuntimeOptions();

            // 调用API获取响应
            RecognizeBusinessLicenseResponse resp = client.recognizeBusinessLicenseWithOptions(request, runtime);


            // 解析核心字段信息（关键路径：resp.body.data -> rootJson.data）
            String respDataStr = resp.getBody().getData();

            // 第一层解析：获取包含核心信息的根JSON
            JSONObject rootJson = JSON.parseObject(respDataStr);
            // 第二层解析：直接提取"核心字段信息"（对应rootJson中的"data"字段）
            JSONObject businessCoreInfo = rootJson.getJSONObject("data");

            // 仅输出核心字段信息（格式化JSON，便于阅读）
//            System.out.println("=== 营业执照核心字段信息（格式化）===");
            CompanyVO companyVO = new CompanyVO();
            companyVO.setCompanyName(businessCoreInfo.getString("companyName"));


            companyVO.setIndustryName(businessCoreInfo.getString("businessScope"));
            companyVO.setEnterpriseCode(businessCoreInfo.getString("creditCode"));
            companyVO.setCompanyType(businessCoreInfo.getString("companyType"));
            companyVO.setCompanyAddress(businessCoreInfo.getString("businessAddress"));
            companyVO.setLegalRepresentative(businessCoreInfo.getString("legalPerson"));
            companyVO.setEstablishTime(businessCoreInfo.getString("RegistrationDate"));
            String validPeriod = businessCoreInfo.getString("validPeriod");
            String[] split = validPeriod.split("至");
            if (split.length > 1) {
                companyVO.setOutTime(split[1]);
            }

            return companyVO;

        } catch (TeaException e) {
            // API调用异常（阿里云OCR接口特有异常）
            System.err.println("=== API调用异常（TeaException）===");
            System.err.println("错误信息：" + e.getMessage());
            System.err.println("诊断建议：" + (e.getData() != null ? e.getData().get("Recommend") : "无"));
        } catch (Exception e) {
            // 系统异常（如文件读取失败、JSON解析错误等）
            System.err.println("=== 系统异常 ===");
            System.err.println("错误信息：" + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
}
